package com.example.demo.config;

import com.baomidou.mybatisplus.extension.api.R;
import com.example.demo.domain.dto.UserLoginDto;
import com.example.demo.service.interfaces.LoginService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    public final static String USER_KEY = "user";
    @Autowired
    LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserLoginDto attribute = (UserLoginDto) session.getAttribute(USER_KEY);
        if (attribute != null) {
            return true;
        }
        UserLoginDto user = loginService.getUser(request);
        if (user != null) {
            loginService.addUser(request, response, user.getId(), user.getPermissions());
            return true;
        }
        // todo 重定向至登录页
        log.info("未登录，请先登录");
        R r = R.failed("please login first");
        response.getOutputStream().write((new Gson().toJson(r)).getBytes(StandardCharsets.UTF_8));
        return false;
    }
}
